﻿using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace SEIPropertyDataService.Entity.Converters
{
    public class ThreeDecimalPlacesConverter : JsonConverter<double>
    {
        public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            => reader.GetDouble();

        public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options)
        {
            if (double.IsNaN(value) || double.IsInfinity(value))
            {
                writer.WriteNullValue();
                return;
            }

            //value = Math.Round(value, 3);
            //writer.WriteNumberValue(value);

            // 使用G3格式化，保证3位有效数字
            string str = value.ToString("G3");

            // 尝试转回double，保证JSON输出为数值类型
            if (double.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out double result))
            {
                writer.WriteNumberValue(result);
            }
            else
            {
                // 极端情况写为字符串
                writer.WriteStringValue(str);
            }
        }
    }
}
